package tt.dz.egobus.servicemanager.base.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import tt.dz.egobus.servicemanager.bean.ServiceManagerCodeStatus;
import tt.dz.egobus.servicemanager.vo.JsonBack;

/**
 * @author Anson
 * @date 17-3-14
 * @name
 * @since 1.0.1
 */
@ControllerAdvice
@ResponseBody
public class ExceptionAdvice {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionAdvice.class);

    /**
     * 非法的参数异常
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonBack<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        LOGGER.error("参数验证失败", e);
        BindingResult result = e.getBindingResult();
        StringBuffer sb = new StringBuffer();
        for (ObjectError error : result.getAllErrors()) {
            String field = error.getCode();
            String code = error.getDefaultMessage();
            String message = String.format("%s:%s", field, code);
            sb.append(message);
        }
        return JsonBack.instance(ServiceManagerCodeStatus.PARAM_ILLEGAL_ERROR.getCodeStatus(), sb.toString());
    }

}